package com.fly.feishu.web.lisener;

import com.alibaba.fastjson.JSONObject;
import com.fly.feishu.api.dto.EmployeeSyncDto;
import com.fly.feishu.api.dto.WorkflowApproval;
import com.fly.feishu.api.dto.WorkflowApprovalCondition;
import com.fly.feishu.api.service.FeishuApprovalService;
import com.fly.feishu.api.service.FeishuContractService;
import com.fly.feishu.domain.service.EmployeeService;
import com.fly.feishu.domain.service.WorkApprovalService;
import com.fly.feishu.infrastructure.persistent.po.Employee;
import com.fly.feishu.infrastructure.persistent.po.WorkApproval;
import com.fly.feishu.web.lisener.annotation.FeishuTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@FeishuTopic(topic = {"work_approval"})
public class FeishuWorkApprovalListener implements FeishuTopicListener {

    @Autowired
    private FeishuApprovalService feishuApprovalService;
    @Autowired
    private FeishuContractService feishuContractService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private WorkApprovalService workApprovalService;

    @Override
    public void exec(Object body) {
        if (body == null) {
            return;
        }
        JSONObject json = (JSONObject) body;
        log.info("审批事件订阅回调：{}", json);
        String instanceCode = json.getString("instance_code");
        String workReason = json.getString("work_reason");
        // 审批发起时间
        Date startTime = new Date(json.getLong("start_time") * 1000);
        // 审批结束时间
        Date endTime = new Date(json.getLong("end_time") * 1000);
        // 用户id
        String employeeId = json.getString("employee_id");
        WorkflowApprovalCondition condition = WorkflowApprovalCondition.builder().instanceCode(instanceCode).build();
        WorkflowApproval workApprovalInstance = feishuApprovalService.getWorkApprovalInstance(condition);
        log.debug("审批事件订阅回调：根据instance_code获取实例详情，instanceCode = {}, workApprovalInstance = {}",
                instanceCode, workApprovalInstance);
        List<WorkflowApproval.TimeLine> timeLineList = workApprovalInstance.getTimeLineList();
        String comment = CollectionUtils.isEmpty(timeLineList) ? null : timeLineList.get(timeLineList.size() - 1).getComment();
        EmployeeSyncDto employee = feishuContractService.getEmployee(workApprovalInstance.getOpenId());
        if (employee != null) {
            String mobile = employee.getMobile();
            Employee employeeServiceByUnique = employeeService.findByUnique(StringUtils.replace(mobile, "+86", ""));
            if (employeeServiceByUnique != null) {
                employeeId = employeeServiceByUnique.getId().toString();
            }
        }
        WorkApproval workApproval = WorkApproval.builder()
                .endTime(endTime)
                .startTime(startTime)
                .instanceCode(instanceCode)
                .workReason(workReason)
                .approvalCode(workApprovalInstance.getApprovalCode())
                .approvalName(workApprovalInstance.getApprovalName())
                .openId(workApprovalInstance.getOpenId())
                .serialNumber(workApprovalInstance.getSerialNumber())
                .status(workApprovalInstance.getStatus())
                .uuid(workApprovalInstance.getUuid())
                .comment(comment)
                .userId(employeeId)
                // TODO departId映射
                .departmentId(workApprovalInstance.getDepartmentId())
                .build();

        workApprovalService.save(workApproval);
    }
}
